#include <pthread.h>
#include <unistd.h>
#include "RingBuffer.hpp"

using namespace RingBufferModule;

void* Producer(void* arg)
{
    RingBuffer<int>* ringbuffer = static_cast<RingBuffer<int>*>(arg);
    int data = 0;
    while(true)
    {
        //1.获取数据
        data++;
        //2.把数据放入ringbuffer
        ringbuffer->PushQueue(data);
        std::cout << "生产了一个数据: " << data << std::endl;
    }
    return nullptr;
}

void* Consumer(void* arg)
{
    RingBuffer<int>* ringbuffer = static_cast<RingBuffer<int>*>(arg);
    while(true)
    {
        //1.从ringbuffer拿数据
        int data;
        ringbuffer->PopQueue(&data);
        //2.处理数据
        sleep(1); //模拟数据处理的时长
        std::cout << "消费了一个数据: " << data << std::endl;
    }
    return nullptr;
}

int main()
{
    RingBuffer<int>* ringbuffer = new RingBuffer<int>(8); //需要传递参数告诉编译器构建多大的环形队列

    pthread_t consumer1, consumer2, producer1, producer2, producer3;
    pthread_create(&producer1, nullptr, Producer, (void*)ringbuffer);
    pthread_create(&producer2, nullptr, Producer, (void*)ringbuffer);
    pthread_create(&producer3, nullptr, Producer, (void*)ringbuffer);
    pthread_create(&consumer1, nullptr, Consumer, (void*)ringbuffer);
    pthread_create(&consumer2, nullptr, Consumer, (void*)ringbuffer);

    pthread_join(consumer1, nullptr);
    pthread_join(consumer2, nullptr);
    pthread_join(producer1, nullptr);
    pthread_join(producer2, nullptr);
    pthread_join(producer3, nullptr);

    delete ringbuffer;
    return 0;
}